const Base = require('./base.js');

module.exports = class extends Base {
  async indexAction() {
    const touristAttraction = this.model('tourist_attraction');
    const data = await touristAttraction.select();
    this.assign('touristAttraction', JSON.stringify(data));
    return this.display();
  }

  async editPageAction() {
    const touristAttraction = this.model('tourist_attraction');
    const data = await touristAttraction.select();
    this.assign('touristAttraction', JSON.stringify(data));
    return this.display();
  }

  async listAction() {
    const page = this.get('page') ? this.get('page') : 1;
    const limit = this.get('limit') ? this.get('limit') : 10;
    const data = await this.model('beacon').page(page).limit(limit).countSelect();
    data.code = 0;
    data.msg = '';
    return this.json(data);
  }

  async deleteAction() {
    const id = this.get('id');
    await this.model('beacon').where({id: id}).delete();
    return this.success();
  }

  async editAction() {
    const attraction = this.get('attraction');
    const major = this.get('major');
    const minor = this.get('minor');
    const id = this.get('id');
    await this.model('beacon').thenUpdate({
      tourist_attraction: attraction,
      major: major,
      minor: minor
    }, {id: id});
    if (id > 0) {
      return this.success();
    } else {
      return this.fail(100, '数据库异常');
    }
  }

  async addAction() {
    const attraction = this.get('attraction');
    const major = this.get('major');
    const minor = this.get('minor');
    const beacon = this.model('beacon');
    const data = await beacon.where({
      major: major,
      minor: minor
    }).find();
    if (data.id) {
      return this.fail(100, 'major,minor已存在相同,请检查后再提交');
    }
    const id = await beacon.add({
      tourist_attraction: attraction,
      major: major,
      minor: minor
    });
    if (id > 0) {
      return this.success();
    } else {
      return this.fail(100, '数据库异常');
    }
  }
};
